<template>
  <div id="questionMessage">
    <a-table
      :columns="columns"
      :data="data"
      :pagination="{
        showTotal: true,
        pageSize: pageInform.pageSize,
        current: pageInform.current,
        total,
      }"
      @page-change="pageChange"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doUpdate(record.id)">修改</a-button>
          <a-button status="danger" @click="doDelete(record)">
            <template #default>删除</template>
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { IconDelete } from "@arco-design/web-vue/es/icon";
import { useRouter } from "vue-router";

const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "内容",
    dataIndex: "content",
    ellipsis: true,
  },
  {
    title: "标签",
    dataIndex: "tags",
  },
  {
    title: "答案",
    dataIndex: "answer",
    ellipsis: true,
  },
  {
    title: "提交数",
    dataIndex: "submitNum",
  },
  {
    title: "通过数",
    dataIndex: "acceptNum",
  },
  {
    title: "题目限制",
    dataIndex: "judgeConfig",
  },
  {
    title: "用户id",
    dataIndex: "userId",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

const pageInform = ref({
  current: 1,
  pageSize: 10,
} as QuestionQueryRequest);

const data = ref([]);
const total = ref();
const router = useRouter();

// 函数
const loads = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    pageInform as QuestionQueryRequest
  );
  if (res.code === 0) {
    data.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("数据出错" + res.message);
  }
};

onMounted(loads);

// 分页函数
const pageChange = (current: number) => {
  pageInform.value = {
    ...pageInform.value,
    current,
  };
  loads();
};

const doUpdate = async (questionId: number) => {
  router.push({
    path: `/question/update/${questionId}`,
  });
};
const doDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    data.value.splice(
      data.value.findIndex((item) => {
        return item === question;
      }),
      1
    );
  } else {
    message.error("删除失败" + res.message);
  }
};
</script>

<style scoped>
#questionMessage {
}
</style>
